/*
 * main.cpp
 *
 *  Created on: 29.12.2012
 *      Author: Vadim
 */

#include <bcm2835.h>
#include "daemonizer/daemonizer.h"
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
// Blinks on RPi pin GPIO 11
#define P1_GPIO23 RPI_GPIO_P1_16
#define  P1_GPIO24 RPI_GPIO_P1_18

#define GREEN_LED 	P1_GPIO23
#define RED_LED 	P1_GPIO24
const char * const gLockFilePath = "/var/run/rasp-blink.pid";
/*************************************************************************/
void tidyUpFunction(void) {

	//Set LED GPIOs to low level
	bcm2835_gpio_write(GREEN_LED, LOW);
	bcm2835_gpio_write(RED_LED, LOW);

	//Configure LED GPIOs as inputs
	bcm2835_gpio_fsel(GREEN_LED, BCM2835_GPIO_FSEL_INPT);
	bcm2835_gpio_fsel(RED_LED, BCM2835_GPIO_FSEL_INPT);
}
int main(int argc, char **argv) {

	if (!bcm2835_init())
		return 1;
	bcm2835_gpio_fsel(GREEN_LED, BCM2835_GPIO_FSEL_OUTP);
	bcm2835_gpio_fsel(RED_LED, BCM2835_GPIO_FSEL_OUTP);
	bcm2835_gpio_write(GREEN_LED, LOW);
	bcm2835_gpio_write(RED_LED, LOW);
	int result;
	pid_t daemonPID;
	int gLockFileDesc = -1;
	if ((result = BecomeDaemonProcess(gLockFilePath, "blinker", LOG_DEBUG,
			&gLockFileDesc, &daemonPID)) < 0) {
		perror("Failed to become daemon process");
		exit(result);
	}
	setTidyUpMethod(&tidyUpFunction);
	if ((result = ConfigureSignalHandlers()) < 0) {
		syslog(LOG_LOCAL0 | LOG_INFO,
				"ConfigureSignalHandlers failed, errno=%d", errno);
		unlink(gLockFilePath);
		exit(result);
	}
	while (1) {
		{
			cout << "LED on parent !\n";
			// Turn it on
			bcm2835_gpio_write(GREEN_LED, HIGH);
			bcm2835_delay(100);
			bcm2835_gpio_write(RED_LED, LOW);
			bcm2835_delay(100);
			cout << "LED off child !\n";
			bcm2835_gpio_write(GREEN_LED, LOW);
			bcm2835_delay(100);
			bcm2835_gpio_write(RED_LED, HIGH);
			bcm2835_delay(100);
		}
	}
	return 0;
}
